package com.chen.pfm.utils;

import ohos.app.Context;
import ohos.bundle.ApplicationInfo;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.net.NetStatusCallback;
import okhttp3.*;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.StandardCharsets;

//网络通信
public class HttpRequestUtil {
    static final HiLogLabel hiLogLabel = new HiLogLabel(HiLog.LOG_APP, 0x2022001, "HttpRequestUtil");

    public static String sendRequest(Context context, String stringUrl, String Method, String token, String data) {
        String result = null;
        NetManager netManager = NetManager.getInstance(context);
        if (!netManager.hasDefaultNet()) {
            return null;
        }
        NetHandle netHandle = netManager.getDefaultNet();
        NetStatusCallback callback = new NetStatusCallback() {

        };
        netManager.addDefaultNetStatusCallback(callback);
        HttpURLConnection connection = null;

        try {
            URL url = new URL(stringUrl);
            connection = (HttpURLConnection) netHandle.openConnection(url, Proxy.NO_PROXY);
            connection.setRequestMethod(Method);

            if (data != null && ("put".equalsIgnoreCase(Method) || "post".equalsIgnoreCase(Method))) {
                connection.setDoOutput(true);
                connection.setRequestProperty("Conten-Type", "application/json; charset=utf-8");
            }
            if (token != null) {
                connection.setRequestProperty("token", token);
            }
            connection.connect();

            if (data != null && ("put".equalsIgnoreCase(Method) || "post".equalsIgnoreCase(Method))) {
                byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
                OutputStream os = connection.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream is = connection.getInputStream();

                BufferedReader reader = null;
                reader = new BufferedReader(new InputStreamReader(is));
                result = "";
                String line;//行数据
                while ((line = reader.readLine()) != null) {
                    result += line;
                }

                HiLog.info(hiLogLabel, "分类标签的渲染数据集 " + result);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }


        return result;
    }

    public static String sendPostRequest(Context context, String stringUrl, String token, String data) {
        return sendRequest(context, stringUrl, "POST", token, data);
    }

    public static String sendGetRequest(Context context, String uri) {
        return sendRequest(context, uri, "GET", null, null);
    }

    public static String sendPostRequestByOkHttp(String url, String json) throws IOException {
        //这个程序向服务发送数据。
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }

    }

    public static String sendPostRequestByOkHttp(String url, RequestBody requestBody) throws IOException {
        //这个程序向服务发送数据。
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
/*
       RequestBody requestBody = new FormBody.Builder()
                .add("userid", "qinzishuai")
                .add("username", "qinzishuai")
                .add("password", "000000")
                .build();
*/
        //设置好requestBody参数
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }

    }

    public static String sendGetRequestByOkHttp(String url) {
        String result = null;
        OkHttpClient client = new OkHttpClient();
        //创造请求对象
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {

            e.printStackTrace();
        }
        return result;
    }
}
